<template>
  <div id="exam-list">
    <!-- 网格列表 -->
    <div class="grid-container">
      <el-row :gutter="20">
        <!-- 添加考试窗格 -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="create-card" shadow="hover" @click="showDialog = true">
            <div class="create-text">添加考试</div>
          </el-card>
        </el-col>

        <!-- 考试列表 -->
        <el-col
          v-for="exam in exams"
          :key="exam.id"
          :xs="24" :sm="12" :md="8" :lg="6"
        >
          <el-card class="exam-card" shadow="hover" @click="selectExam(exam)">
            <div class="card-header">
              <span class="exam-name">{{ exam.name }}</span>
              <span class="exam-id">ID: {{ exam.id }}</span>
            </div>
            <div class="card-body">
              <p>课程名称: {{ exam.course }}</p>
              <p>开始时间: {{ exam.startTime }}</p>
              <p>总分: {{ exam.totalScore }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页查询区 -->
    <div class="query-box-liner">
      <el-form :inline="true" class="query-form">
        <el-form-item class="stuPage" label="页码">
          <el-input-number v-model="pageNum" :min="1" />
        </el-form-item>
        <el-form-item class="stuPage" label="每页条数">
          <el-input-number v-model="pageSize" :min="1" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchExams">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 添加考试对话框 -->
    <el-dialog title="添加考试" v-model="showDialog" width="500px">
      <el-form label-width="120px">
        <el-form-item label="考试名称">
          <el-input v-model="newExam.name" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="考试描述">
          <el-input type="textarea" :rows="3" v-model="newExam.description" placeholder="请输入考试描述" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="newExam.startTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="总时长">
          <el-input v-model="newExam.totalTime" placeholder="例如 120分钟" />
        </el-form-item>
        <el-form-item label="总分">
          <el-input-number v-model="newExam.totalScore" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitNewExam">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useCookies } from 'vue3-cookies';
import { ElMessage } from 'element-plus'

const router = useRouter()
const { cookies } = useCookies()

const pageNum = ref(1)
const pageSize = ref(10)
const exams = ref([])

const showDialog = ref(false)
const newExam = ref({
  name: '',
  description: '',
  startTime: null,
  totalTime: '',
  totalScore: 0,
  type: 1
})

async function fetchExams() {
  try {
    const res = await axios.get('/api/exam/page', {
      params: { pageNum: pageNum.value, pageSize: pageSize.value }
    })
    if (res.data?.code === 200) {
      const records = res.data.data.records || []
      if(records.length <= 0){
        ElMessage.error("未查询到考试")
        return
      }
      // 获取已选课程信息
      const stored = cookies.get('selectedCourse')
      let selectedCourse = null
      try {
        selectedCourse = stored
      } catch {
        console.error('解析 selectedCourse 失败')
      }
      // 处理课程字段替换
      exams.value = records.map(item => {
        if (selectedCourse && item.course === selectedCourse.id) {
          return { ...item, course: selectedCourse.courseName }
        }
        return item
      })
    }
  } catch (e) {
    ElMessage.error("未查询到考试")
    console.log('获取考试列表失败', e)
  }
}

function selectExam(exam) {
  cookies.set('selectedExam', JSON.stringify(exam))
  router.push('/teacher/courseManage/examQuestionManage')
}

//添加考试
async function submitNewExam() {
  try {
    // 获取课程信息（用于设置 course 字段）
    const selectedCourseRaw = cookies.get('selectedCourse')
    let selectedCourse = null
    try {
      selectedCourse = typeof selectedCourseRaw === 'string'
        ? JSON.parse(selectedCourseRaw)
        : selectedCourseRaw
    } catch {
      console.error('selectedCourse 解析失败')
      alert('请先选择课程')
      return
    }

    if (!selectedCourse || !selectedCourse.id) {
      alert('课程信息缺失，无法创建考试')
      return
    }

    // 构造发送的数据
    const payload = {
      name: newExam.value.name,
      description: newExam.value.description,
      startTime: formatDateTime(newExam.value.startTime),
      totalTime: newExam.value.totalTime,
      totalScore: newExam.value.totalScore,
      type: newExam.value.type,
      course: selectedCourse.id
    }

    // 发送 POST 请求
    const res = await axios.post('/api/exam/add', payload)

    if (res.data?.code === 200) {
      alert('考试添加成功')
      showDialog.value = false
      await fetchExams() // 重新拉取考试列表
      resetNewExam()     // 清空表单
    } else {
      alert(`创建失败：${res.data?.msg || '未知错误'}`)
    }
  } catch (e) {
    console.error('提交考试失败', e)
    alert('请求失败，请稍后再试')
  }
}

//辅助函数

function resetNewExam() {
  newExam.value = {
    name: '',
    description: '',
    startTime: null,
    totalTime: '',
    totalScore: 0,
    type: 1
  }
}

// 格式化时间为字符串："YYYY-MM-DD HH:mm:ss"
function formatDateTime(date) {
  if (!date) return ''
  const pad = n => (n < 10 ? '0' + n : n)
  const y = date.getFullYear()
  const m = pad(date.getMonth() + 1)
  const d = pad(date.getDate())
  const h = pad(date.getHours())
  const mi = pad(date.getMinutes())
  const s = pad(date.getSeconds())
  return `${y}-${m}-${d} ${h}:${mi}:${s}`
}

onMounted(fetchExams)
</script>

<style scoped lang="less">
#exam-list {
  padding: 20px;
  // background-color: #f5f7fa;
}
.query-box-liner {
  margin-bottom: 20px;
  background: #fff;
  padding: 16px;
  border-radius: 4px;
}
.grid-container {
  background: hsla(0, 0%, 100%, 0.5);
  padding: 20px;
  border-radius: 4px;
}
.create-card {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 120px;
  background: #fafafa;
  border: 2px dashed #ccc;
  margin-bottom: 20px;
}
.create-card:hover {
  border-color: #409EFF;
}
.create-text {
  color: #909399;
  font-size: 16px;
}
.exam-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.exam-name {
  font-size: 18px;
  font-weight: 600;
}
.exam-id {
  font-size: 12px;
  color: #909399;
}
.card-body p {
  margin: 4px 0;
  font-size: 14px;
  color: #606266;
}
</style>
